package com.freshfresh.view.db;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;

public class CodeTableManager {
	
	/**
	 * 通过代码值获取代码名称
	 * @param context
	 * @param codeTable
	 * @param code
	 * @return
	 */
	public static String getNameByCode(Context context,String codeTable,String code){
		String name = null;
		String sql = "select name from pub_codetable where codetable = '"+codeTable+"' and code='"+code+"'";
		Cursor cursor = DBManager.getDBconnection(context).rawQuery(sql, null);
		if(cursor != null && cursor.moveToFirst()){
			name = cursor.getString(0);
		}
		if(cursor != null && !cursor.isClosed()){
			cursor.close();
		}
		return name;
	}
	
	/**
	 * 通过名称获取代码值
	 * @param context
	 * @param codeTable
	 * @param name
	 * @return
	 */
	public static String getCodeByName(Context context,String codeTable,String name){
		String code = null;
		String sql = "select code from pub_codetable where codetable = '"+codeTable+"' and name = '"+name.trim()+"'";
		Cursor cursor = DBManager.getDBconnection(context).rawQuery(sql,null);
		if(cursor != null && cursor.moveToFirst()){
			code = cursor.getString(0);
		}
		if(cursor != null && !cursor.isClosed()){
			cursor.close();
		}
		return code;
	}
	
	/**
	 * 通过代码表获取所有名称
	 * @param context
	 * @param codeTable
	 * @return ArrayList<String> or null
	 */
	public static ArrayList<String> getListNameByCodeTable(Context context,
			String codeTable) {
		ArrayList<String> list = null;
		String sql = "select name from pub_codetable where codetable = '"
				+ codeTable + "' order by orderid";
		Cursor cursor = DBManager.getDBconnection(context).rawQuery(sql, null);
		if (cursor != null && cursor.moveToFirst()) {
			list = new ArrayList<String>();
			do {
				list.add(cursor.getString(0));
			} while (cursor.moveToNext());
		}
		if(cursor != null && !cursor.isClosed()){
			cursor.close();
		}
		return list;
	}
	
	/**
	 * 通过代码表名称上级代码获取所有名称
	 * @param context
	 * @param codeTable
	 * @param parrentCode
	 * @return ArrayList<String> or null
	 */
	public static ArrayList<String> getListNameByCodeTable(Context context,
			String codeTable, String parrentCode) {
		ArrayList<String> list = null;
		String sql = "select name from pub_codetable where codetable = '"
				+ codeTable + "' and parentcode = '" + parrentCode
				+ "' order by orderid";
		Cursor cursor = DBManager.getDBconnection(context).rawQuery(sql, null);
		if (cursor != null && cursor.moveToFirst()) {
			list = new ArrayList<String>();
			do {
				list.add(cursor.getString(0));
			} while (cursor.moveToNext());
		}
		if(cursor != null && !cursor.isClosed()){
			cursor.close();
		}
		return list;
	}
}
